﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Mimoza.Transport
{
    public class EndPoint
    {
        public static IPEndPoint CreateEndPoint(string remoteIpOrHostName, int port)
        {
            IPAddress ipAddr = null;
            if (remoteIpOrHostName.Length > 0)
            {
                try
                {
                    ipAddr = IPAddress.Parse(remoteIpOrHostName);
                }
                catch (Exception) { }
            }

            if (remoteIpOrHostName.Length > 0 && ipAddr == null)
            {
                IPHostEntry ipEntry = Dns.GetHostEntry(remoteIpOrHostName);
                if (ipEntry.AddressList.Length > 0)
                {
                    foreach (IPAddress addr in ipEntry.AddressList)
                    {
                        if (!IsIPv6Address(addr)) // skip IPV6 addressess
                        {
                            ipAddr = addr;
                            break;
                        }
                    }
                    if (ipAddr == null)
                    {
                        ipAddr = ipEntry.AddressList[0];
                    }
                }
            }
            else
            {
                if (ipAddr == null)
                {
                    ipAddr = IPAddress.Broadcast;
                }
            }

            Common.Logger.Log.Info("FillRemoteEndPoint address - " + ipAddr.ToString() +
                " port - " + port.ToString() + ".");

            return new IPEndPoint(ipAddr, port);
        }

        public static string GetHostAddrByName(string hostName)
        {
            IPHostEntry hostEntry = System.Net.Dns.GetHostByName(hostName);

            string hostAddr = (hostEntry.AddressList == null) ? "" : hostEntry.AddressList.First().ToString();

            return hostAddr;
        }

        public static bool IsIPv6Address(IPAddress addr)
        {
#if !WindowsCE
            if (!addr.IsIPv6LinkLocal && !addr.IsIPv6Multicast && !addr.IsIPv6SiteLocal &&
                                        addr.AddressFamily != AddressFamily.InterNetworkV6)
            {
                return false;
            }
            else
                return true;
#else
            return false;
#endif
        }

    }
}
